//package com.oauth.oauth.config;
//
//import com.oauth.oauth.VO.OAuth2OpenCheckTokenRespVO;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.http.HttpEntity;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.HttpMethod;
//import org.springframework.http.MediaType;
//import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.authority.AuthorityUtils;
//import org.springframework.security.core.userdetails.User;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.crypto.codec.Base64;
//import org.springframework.util.LinkedMultiValueMap;
//import org.springframework.util.MultiValueMap;
//import org.springframework.web.client.RestTemplate;
//
//import java.nio.charset.StandardCharsets;
//import java.util.Collections;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//public class CustomRemoteTokenServices extends RemoteTokenServices {
//
//    private static final Logger logger = LoggerFactory.getLogger(CustomRemoteTokenServices.class);
//
//    private final RestTemplate restTemplate;
//
//    private final String checkTokenEndpointUrl; // 保存 checkTokenEndpointUrl 的值
//    private final String clientSecret; // 保存 checkTokenEndpointUrl 的值
//    private final String clientId; // 保存 checkTokenEndpointUrl 的值
//
//    public CustomRemoteTokenServices(String checkTokenEndpointUrl, String clientId, String clientSecret) {
//        super();
//        this.checkTokenEndpointUrl = checkTokenEndpointUrl; // 在构造函数中保存
//        this.clientId = clientId; // 在构造函数中保存
//        this.clientSecret = clientSecret; // 在构造函数中保存
//        setCheckTokenEndpointUrl(checkTokenEndpointUrl);
//        setClientId(clientId);
//        setClientSecret(clientSecret);
//        this.restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
//    }
//
//    @Override
//    public OAuth2Authentication loadAuthentication(String accessToken) {
//        try {
//
//            HttpHeaders headers = new HttpHeaders();
//            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
//            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//            String credentials = clientId + ":" + clientSecret;
//            String encodedCredentials = new String(Base64.encode(credentials.getBytes(StandardCharsets.UTF_8)));
//            headers.set("Authorization", "Basic " + encodedCredentials);
//            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
//            params.add("token", accessToken);
//
//            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
//            OAuth2OpenCheckTokenRespVO body = restTemplate.exchange(checkTokenEndpointUrl, HttpMethod.POST, requestEntity, OAuth2OpenCheckTokenRespVO.class).getBody();
//            return extractAuthentication(body);
//
//        } catch (Exception e) {
//            logger.error("Failed to load authentication from token: {}", accessToken, e);
//            throw new InvalidTokenException("Invalid access token: " + accessToken);
//        }
//    }
//
//
//    private OAuth2Authentication extractAuthentication(OAuth2OpenCheckTokenRespVO accessToken) {
//        if (accessToken == null) {
//            return null;
//        }
//
//        String tokenValue = accessToken.getAccessToken();
//
//        // 1. 对 tokenValue 进行自定义操作，例如：
//        //    - 解密 Token
//        //    - 从 Token 中提取自定义信息
//        //    - 对 Token 进行格式转换
//        String processedToken = processToken(tokenValue);
//
//        // 2. 使用 processedToken 构建 OAuth2Authentication
//        OAuth2Authentication authentication;
//        try {
//            // 使用 RestTemplate 或其他方式向认证服务器发起校验请求
//            Map<String, Object> tokenInfo = validateToken(processedToken);
//
//            // 从 tokenInfo 中提取用户信息
//            String userId = (String) tokenInfo.get("user_id");
//            String username = (String) tokenInfo.get("username");
//            List<String> authorities = (List<String>) tokenInfo.get("authorities");
//
//            // 创建 Authentication 对象
//            UserDetails userDetails = new User(username, "", AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",", authorities)));
//            Authentication userAuthentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
//
//            // 创建 OAuth2Authentication 对象
//            OAuth2Request oAuth2Request = new OAuth2Request(null, null, null, true, null, null, null, null, null);
//            authentication = new OAuth2Authentication(oAuth2Request, userAuthentication);
//
//        } catch (Exception e) {
//            logger.error("Failed to validate token: {}", processedToken, e);
//            throw new InvalidTokenException("Invalid access token: " + tokenValue);
//        }
//
//        return authentication;
//    }
//
//    // 自定义 Token 处理方法
//    private String processToken(String tokenValue) {
//        // 根据您的需求实现自定义逻辑
//        // ...
//        return tokenValue;
//    }
//
//    // 自定义 Token 校验方法
//    private Map<String, Object> validateToken(String token) {
//        // 使用 RestTemplate 或其他方式向认证服务器发起校验请求
//        // ...
//        Map<String, Object> tokenInfo = new HashMap<>();
//        return tokenInfo;
//    }
//
//}